<?php
//==============================================================================
//nabtonEdit.php
//Desc: Used for editing streams and applications
//=============================================================================
session_start();

require_once('dataManager/definitions.php');
require_once('dataManager/DataManager.php');

//Check if logged in -> if not die
if($_SESSION['valid_login'] == false)
{
	die();
}

//TODO sids not secured - verify ownership and access!
//TODO Add sql injection defense
// Main program ======================
$dbM = new DataManager(DB_USER, DB_PASSWORD, "localhost", NB_DATABASE_ADMIN);

$action = $_POST['action'];
echo("Action:$action");
switch($action)
{
	case "createApp": // create
        $appTitle      = $_POST['titleApp'];
        $appAccess     = $_POST['accessApp'];
        $appChartType  = $_POST['chartTypeApp'];
        $selectedSids  = $_REQUEST['selectedSids'];


        $valueArray  = array($appTitle,
                             $appAccess,
                             $_SESSION['uid'],
                             $appChartType);
 
        $columnArray = array(NB_ADMIN_APPLICATIONS_COLUMN_TITLE,
                             NB_ADMIN_APPLICATIONS_COLUMN_SHARED,
                             NB_ADMIN_APPLICATIONS_COLUMN_OWNERID,
                             NB_ADMIN_APPLICATIONS_COLUMN_CHARTTYPE); 
  
        $dbM->insertRow(NB_ADMIN_TABLE_APPLICATIONS, $columnArray, $valueArray);
    
        //Get appid
        $condition = NB_ADMIN_APPLICATIONS_COLUMN_OWNERID."=".$_SESSION['uid']." ORDER BY ".NB_GENERAL_COLUMN_TIMESTAMP." DESC";

        $dbM->selectAllFromTable(NB_ADMIN_TABLE_APPLICATIONS, $condition); 
  
        if($data = $dbM->retrieveResult())
        {
            $appid = $data[NB_ADMIN_APPLICATIONS_COLUMN_APPID];
        
            $columnArray = array(NB_ADMIN_APPSTREAMLINK_COLUMN_APPID,
                                 NB_ADMIN_APPSTREAMLINK_COLUMN_SID);
            
            //Create links to sids
            foreach ($selectedSids as $sid)
            {
                $valueArray  = array($appid,
                                     $sid);
                
                $dbM->insertRow(NB_ADMIN_TABLE_APPSTREAMLINK, $columnArray , $valueArray);
            }
        }
        else
        {
            echo "Problem creating Application!";
        }    

	   break;
    case "editApp": //Edit
        $appId      = $_POST['idApp'];

	   break; 
	case "deleteApp": //Delete
        //Check for valid appid - only delete your own
        $appId      = $_POST['idApp'];
    
        //Delete app
        $dbM->deleteRow(NB_ADMIN_TABLE_APPLICATIONS, NB_ADMIN_APPLICATIONS_COLUMN_APPID, $appId);
    
        //Deleted all links to app
        $dbM->deleteRow(NB_ADMIN_TABLE_APPSTREAMLINK, NB_ADMIN_APPSTREAMLINK_COLUMN_APPID, $appId);
        
	   break;
}





?>
